//
//  UserRightViewController.m
//  SportSocial
//
//  Created by yull on 15/1/12.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "UserRightViewController.h"
#import "YPhotoView.h"
#import "PhotoSectionView.h"
#import "PhotoCell.h"
#import "PhotoNet.h"

#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshLoadMoreContainView.h"

#define  Photo_Page_Count 10

@interface UserRightViewController () <UICollectionViewDataSource,UICollectionViewDelegate,YPhotoViewDelegate>

@property (nonatomic, strong) UICollectionView *photoCollectionView;

@property (nonatomic, strong) NSMutableArray *photoArray;

@property (nonatomic, strong) YPhotoView *photoView;

@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@end

@implementation UserRightViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initCollectionView];
    
    [self initPhotoView];
    
    [self loadPhotoFromServer];
    
    @weakify(self);
    [self.photoCollectionView nd_addPullToLoadMoreWithActionHandler:^(id sender) {
        @strongify(self);
        [self loadPhotoFromServer];
    }];
}

- (void)initPhotoView
{
    self.photoView = [[YPhotoView alloc] initWithFrame:self.view.bounds];
    self.photoView.delegate = self;
}

- (void)initCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 8, 10, 8);
    flowLayout.minimumInteritemSpacing = 5;
    flowLayout.minimumLineSpacing = 5;
    CGFloat width = (SCREEN_WIDTH - 8 * 2 - 2 * 5) / 3;
    flowLayout.itemSize = CGSizeMake(width, width);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.headerReferenceSize = CGSizeMake(self.view.width, 44);
    
    self.photoCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    self.photoCollectionView.dataSource = self;
    self.photoCollectionView.delegate = self;
    self.photoCollectionView.alwaysBounceVertical = YES;
    self.photoCollectionView.backgroundColor = [UIColor clearColor];
    [self.photoCollectionView registerClass:[PhotoCell class] forCellWithReuseIdentifier:@"PhotoCell"];
    [self.photoCollectionView registerClass:[PhotoSectionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PhotoSection"];
    self.photoCollectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:self.photoCollectionView];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.photoArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSDictionary *dict = [self.photoArray objectAtIndex:section];
    NSArray *photos = [dict.allValues firstObject];
    return photos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoCell *photoCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCell" forIndexPath:indexPath];
    
    NSDictionary *dict = [self.photoArray objectAtIndex:indexPath.section];
    NSArray *photos = [dict.allValues firstObject];
    NSString *url = [photos objectAtIndex:indexPath.row];
    [photoCell drawCellWithUrl:url];
    return photoCell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    PhotoSectionView *sectionView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PhotoSection" forIndexPath:indexPath];
    NSDictionary *dict = [self.photoArray objectAtIndex:indexPath.section];
    NSString *timeStr = dict.allKeys.firstObject;
    NSArray *photos = [dict.allValues firstObject];
    [sectionView drawSectionViewWithCount:photos.count Time:timeStr];
    return sectionView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *allPhotos = [NSMutableArray array];
    for (NSDictionary *dictArray in self.photoArray) {
        [allPhotos addObjectsFromArray:[dictArray allValues].firstObject];
    }
    
    NSMutableArray *bigPhotoArray = [NSMutableArray array];
    
    for (NSString *photoUrl in allPhotos) {
        YPhoto *photo = [[YPhoto alloc] init];
        photo.thumbUrl = photoUrl;
        photo.imageUrl = photoUrl;
        
        for (PhotoCell *cell in self.photoCollectionView.visibleCells) {
            if ([photoUrl isEqualToString:cell.imageUrl]) {
                CGRect rect = [self.navigationController.view convertRect:cell.imageView.frame fromView:cell.contentView];
                photo.imageRect = rect;
            }
        }
        [bigPhotoArray addObject:photo];
    }
    self.photoView.photoArray = bigPhotoArray;
    
    PhotoCell *cell = (PhotoCell *)[collectionView cellForItemAtIndexPath:indexPath];
    self.photoView.showIndex = [allPhotos indexOfObject:cell.imageUrl];
    
    [self.parentViewController.navigationController.view addSubview:self.photoView];
    
    self.parentViewController.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [self.photoView showPhotoViewWithImage:cell.imageView.image];
}

- (void)loadPhotoFromServer
{
    if (!self.photoArray) {
        self.photoArray = [NSMutableArray array];
    }
    
    [PhotoNet photoPaginateWithUserId:self.userId PageNumber:self.currentPage + 1 pageSize:Photo_Page_Count successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dataDictionary = [responseObject objectForKey:@"data"];
            
            if (self.currentPage == 0) {
                [self.photoArray removeAllObjects];
            }
            
            self.totalPage = [[dataDictionary objectForKey:@"totalPage"] integerValue];
            self.currentPage = [[dataDictionary objectForKey:@"pageNumber"] integerValue];
            
            NSArray *listArray = [dataDictionary objectForKey:@"list"];
            
            NSString *lastTimeGroupStr = nil;
            NSDictionary *lastPhotoGroupDic = nil;
            if (self.photoArray.count) {
                lastPhotoGroupDic = self.photoArray.lastObject;
                lastTimeGroupStr = [[lastPhotoGroupDic allKeys] firstObject];
            }
            
            for (NSDictionary *photoDic in listArray) {
                NSString *timeStr = [[photoDic objectForKey:@"upload_date"] substringToIndex:10];
                
                if ([timeStr isEqualToString:lastTimeGroupStr] && timeStr.length) {
                    
                    NSMutableArray *photoArray = [lastPhotoGroupDic objectForKey:lastTimeGroupStr];
                    [photoArray addObject:[photoDic objectForKey:@"file_url"]];
                    
                } else {
                    
                    NSMutableArray *photoArray = [NSMutableArray arrayWithObject:[photoDic objectForKey:@"file_url"]];
                    NSDictionary *photoGroupDic = [NSDictionary dictionaryWithObject:photoArray forKey:timeStr];
                    [self.photoArray addObject:photoGroupDic];
                    
                    lastTimeGroupStr = timeStr;
                    lastPhotoGroupDic = photoGroupDic;
                    
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentPage == self.totalPage) {
                    ((NDRefreshLoadMoreContentView *)(self.photoCollectionView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.photoCollectionView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                }
                [self.photoCollectionView reloadData];
                [self endLoad];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
                [self endLoad];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
            [self endLoad];
        });
    }];
}

- (void)endLoad
{
    [self.photoCollectionView nd_endLoadMore];
}

#pragma mark - YPhotoDelegate
- (void)photoViewHide
{
    self.parentViewController.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    [self.photoView removeFromSuperview];
}

- (void)setTopView:(UIView *)topView
{
    topView.top = -topView.height;
    [self.photoCollectionView addSubview:topView];
    
    self.photoCollectionView.contentInset = UIEdgeInsetsMake(topView.height, 0, 0, 0);
    self.photoCollectionView.contentOffset = CGPointZero;
}

- (void)removeTopView
{
    self.photoCollectionView.contentInset = UIEdgeInsetsZero;
}

@end
